package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Banner;
import cn.wolfcode.luowowo.query.BannerQuery;
import cn.wolfcode.luowowo.repository.BannerRepository;
import cn.wolfcode.luowowo.service.IBannerService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
//@Transactional mongodb事务必须复制集方式
public class BannerServiceImpl implements IBannerService {

    //spring-data-mongodb中的查询方式有两种repository(不能分页操作)和template
    //Spring-boot集成redis持久化数据库
    @Autowired
    private BannerRepository repository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Banner banner) {

        banner.setId(null);
        repository.save(banner);
    }

    @Override
    public void delete(String id) {

        repository.deleteById(id);
    }

    @Override
    public void update(Banner banner) {

        repository.save(banner);
    }

    @Override
    public Banner get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Banner> listAll() {
        return repository.findAll();
    }

    //分页查询(高级查询)
    @Override
    public Page<Banner> query(BannerQuery qo) {
        Query query = new Query();
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,
                qo.getPageSize(), Sort.Direction.ASC,"_id");

        return DBHelper.query(template, Banner.class, query, pageable);
    }

    // 添加按钮:添加/更新
    @Override
    public void saveOrUpdate(Banner banner) {
        if(StringUtils.hasLength(banner.getId())){
            // 调用本类中的更新方法
            // 特殊案例,页面更新数据,刚好符合集合中字段个数
            // 所以这种等价于全量更新(只有符合以上可以这么使用)
            this.update(banner);//更新
        }else{
            this.save(banner);//添加
        }
    }

    // 根据类型查询banner广告
    @Override
    public List<Banner> queryBanner(int type) {
        // 必须能显示,按照序号排序
       Pageable pageable = PageRequest.of(0,5, Sort.Direction.ASC,"sequence");

       // 根据状态和类型查询banner广告
        return repository.findByStateAndType(Banner.STATE_NORMAL,type,pageable);
    }
}
